﻿using System;
using System.Collections.Generic;
using System.Linq;
using Citi.Import.Util;

namespace Citi.GocAttributes.Domain
{
    public partial class FrsBu
    {
        private const string FrsBuColumnName = "C_DSMT_TN_FRSBU";
        private const string FrsBuDescriptionColumnName = "FRSBU_PN_DESCR80";

        public static readonly List<Definition<FrsBu>> Definitions = new List<Definition<FrsBu>>
            {
                new Definition<FrsBu> { ModelProperty = x => x.Code, Required = true, ColumnName = FrsBuColumnName, CustomConversionMethod = ValidateCode},
                new Definition<FrsBu> { ModelProperty = x => x.Description, MaxLength = 100, Required = true, ColumnName = FrsBuDescriptionColumnName},
            };

        private static object ValidateCode(ref FrsBu model, string value, List<string> fields, ref string error, List<string> headers = null)
        {
            if (String.IsNullOrEmpty(value))
            {
                error = String.Format(ErrorFieldNull, FrsBuColumnName);
                return Conversion.Validation.Failed;
            }

            var domain = CacheFacade.Get(SelectAll<FrsBu>).LastOrDefault(x => x.Code == int.Parse(value));

            if (domain != null)
            {
                model = domain;
                model.LastUpdate = DateTime.Now;
                return Conversion.Validation.Validated;
            }

            model.LastUpdate = DateTime.Now;
            model.ReferenceDate = DateTime.Today;
            return int.Parse(value);
        }

        public static void Save(IEnumerable<FrsBu> frsBus)
        {
            var toSave = frsBus.Distinct(new FrsBuComparer()).Where(x => x != null && x.Id == 0).ToList();

            if (toSave.Any())
                toSave.First().Save(toSave, 100);

            CacheFacade.Clear(typeof(FrsBu));
        }

        public FrsBu SelectByCode(int code)
        {
            return SelectAll<FrsBu>().FirstOrDefault(x => x.Code == code);
        }
    }

    public class FrsBuComparer : IEqualityComparer<FrsBu>
    {
        public bool Equals(FrsBu x, FrsBu y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
                return false;

            return x.Description == y.Description && x.Code == y.Code && x.Id == y.Id;
        }

        public int GetHashCode(FrsBu item)
        {
            if (ReferenceEquals(item, null)) return 0;

            var hashDescription = item.Description == null ? 0 : item.Description.GetHashCode();
            var hashId = item.Description == null ? 0 : item.Id.GetHashCode();

            return hashDescription ^ hashId;
        }
    }
}
